package com.wangzeqi.changliaoba.worldlet.circle;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.NetworkImageView;
import com.easemob.chat.EMChatManager;
import com.wangzeqi.BmobEntity.FriendCircleText;
import com.wangzeqi.changliaoba.R;
import com.wangzeqi.changliaoba.base.BaseActivity;
import com.wangzeqi.changliaoba.util.OSUtils;
import com.wangzeqi.custom.ChooseDialog;
import com.wangzeqi.custom.CropHelper;
import com.wangzeqi.custom.RefreshableView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.listener.FindListener;

/**
 * Created by dllo on 16/3/7.
 */
public class FriendCircleActivity extends BaseActivity implements View.OnClickListener {

    private ListView listView;
    private ImageView imageViewMore;
    private ImageButton imageButton;
    private ChooseDialog mDialog;
    private CropHelper mCropHelper;
    private FriendCircleAdapter adapter;
    private PopupWindow pwMyPopWindow;// popupwindow
    private ListView lvPopupList;// popupwindow中的ListView
    private int NUM_OF_VISIBLE_LIST_ROWS = 4;// 指定popupwindow中Item的数量
    List<Map<String, String>> moreList;
    RefreshableView refreshableView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.friend_circle_layout);
        adapter = new FriendCircleAdapter(this);
        listView = (ListView) findViewById(R.id.friend_circle_lv);
        imageViewMore = (ImageView) findViewById(R.id.friend_circle_more);
        imageButton = (ImageButton) findViewById(R.id.back_btn);
        refreshableView = (RefreshableView) findViewById(R.id.refreshable_view);
        imageButton.setOnClickListener(this);
        mCropHelper = new CropHelper(this, OSUtils.getSdCardDirectory() + "/head.png");
        mDialog = new ChooseDialog(this, mCropHelper);
        iniData();
        iniPopupWindow();
        addHeadView();
        imageViewMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pwMyPopWindow.isShowing()) {

                    pwMyPopWindow.dismiss();// 关闭
                } else {

                    pwMyPopWindow.showAsDropDown(imageViewMore, 17, 27);// 显示
                }

            }
        });

        getData();
        listView.setAdapter(adapter);
        refreshableView.setOnRefreshListener(new RefreshableView.PullToRefreshListener() {
            @Override
            public void onRefresh() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                refreshableView.finishRefreshing();
            }
        }, 0);

    }

    private void getData() {

        BmobQuery<FriendCircleText> query = new BmobQuery<FriendCircleText>();
        List<BmobQuery<FriendCircleText>> and = new ArrayList<BmobQuery<FriendCircleText>>();
        //大于00：00：00
        BmobQuery<FriendCircleText> q1 = new BmobQuery<FriendCircleText>();
        String start = "2015-05-01 00:00:00";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = sdf.parse(start);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        q1.addWhereGreaterThanOrEqualTo("createdAt", new BmobDate(date));
        and.add(q1);
        query.and(and);
        query.findObjects(this, new FindListener<FriendCircleText>() {
            @Override
            public void onSuccess(List<FriendCircleText> list) {
                adapter.addData(list);
                Toast.makeText(FriendCircleActivity.this, "数据已刷新", Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onError(int i, String s) {
                Toast.makeText(FriendCircleActivity.this, "刷新失败" + i, Toast.LENGTH_SHORT).show();
            }
        });

    }

    private void addHeadView() {
        RelativeLayout hearderView = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.friend_circle_head_item_layout, null);
        NetworkImageView imageView, imageViewUser;
        TextView textView;
        imageViewUser = (NetworkImageView) hearderView.findViewById(R.id.friend_circle_head_user_picture);
        imageView = (NetworkImageView) hearderView.findViewById(R.id.friend_circle_head_background);
        textView = (TextView) hearderView.findViewById(R.id.friend_circle_head_user_name);
        textView.setText(EMChatManager.getInstance().getCurrentUser());
        listView.addHeaderView(hearderView);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_btn:
                finish();
                break;
        }
    }


    private void iniData() {

        moreList = new ArrayList<Map<String, String>>();
        Map<String, String> map;
        map = new HashMap<String, String>();
        map.put("share_key", "更换封面");
        moreList.add(map);
        map = new HashMap<String, String>();
        map.put("share_key", "发朋友圈");
        moreList.add(map);
        map = new HashMap<String, String>();
        map.put("share_key", "发视频");
        moreList.add(map);
        map = new HashMap<String, String>();
        map.put("share_key", "匿名评价");
        map.put("ni_ming","取消匿名");
        moreList.add(map);
    }

    private void iniPopupWindow() {

        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.task_detail_popupwindow, null);
        lvPopupList = (ListView) layout.findViewById(R.id.lv_popup_list);
        pwMyPopWindow = new PopupWindow(layout);
        pwMyPopWindow.setFocusable(true);// 加上这个popupwindow中的ListView才可以接收点击事件
        lvPopupList.setAdapter(new SimpleAdapter(FriendCircleActivity.this, moreList,
                R.layout.friend_iten_popupwindow_layout, new String[]{"share_key"},
                new int[]{R.id.tv_list_item}));
        lvPopupList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    mDialog.popSelectDialog();
                } else if (position == 1) {
                    Intent intent = new Intent(FriendCircleActivity.this, FriendCircleSendActivity.class);
                    startActivity(intent);
                } else if (position == 2) {
                    Toast.makeText(FriendCircleActivity.this,
                            moreList.get(position).get("share_key"),
                            Toast.LENGTH_SHORT).show();
                } else if (position == 3) {

                    Toast.makeText(FriendCircleActivity.this,
                            moreList.get(position).get("share_key"),
                            Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 控制popupwindow的宽度和高度自适应
        lvPopupList.measure(View.MeasureSpec.UNSPECIFIED,
                View.MeasureSpec.UNSPECIFIED);
        pwMyPopWindow.setWidth(lvPopupList.getMeasuredWidth() + 20);
        pwMyPopWindow.setHeight((lvPopupList.getMeasuredHeight() + 40)
                * NUM_OF_VISIBLE_LIST_ROWS);
        // 控制popupwindow点击屏幕其他地方消失
        pwMyPopWindow.setBackgroundDrawable(this.getResources().getDrawable(
                R.mipmap.bg_popupwindow));// 设置背景图片，不能在布局中设置，要通过代码来设置
        pwMyPopWindow.setOutsideTouchable(true);// 触摸popupwindow外部，popupwindow消失。这个要求你的popupwindow要有背景图片才可以成功
//        pwMyPopWindow.showAtLocation(this.findViewById(R.id.more_btn), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 20, 20);

    }


}
